package com.zrgj.manager.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.zrgj.domain.Product;
import com.zrgj.domain.ProductPo;
import com.zrgj.domain.ShoppingCar;
import com.zrgj.manager.mapper.ProductMapper;
import com.zrgj.manager.mapper.ShoppingCarMapper;
import com.zrgj.manager.service.IShoppingCarService;
import org.springframework.stereotype.Component;

import java.util.List;

@Service
@Component
public class ShoppingCarServiceImpl implements IShoppingCarService {
    private ShoppingCarMapper shoppingCarMapper;
    private ProductMapper productMapper;

    public ShoppingCarServiceImpl(ShoppingCarMapper shoppingCarMapper, ProductMapper productMapper) {
        this.shoppingCarMapper = shoppingCarMapper;
        this.productMapper = productMapper;
    }

    @Override
    public List<ShoppingCar> selectByUser(Integer userId) {
        List<ShoppingCar> cartList = shoppingCarMapper.selectByUser(userId);
        for (int i = 0; i < cartList.size(); i++){
            Product keyProduct = new Product();
            keyProduct.setProductId(cartList.get(i).getProductId());
            Product product = productMapper.selectPro(keyProduct).get(0);
            cartList.get(i).setProduct(product);
        }

        return cartList;
    }

    @Override
    public ShoppingCar insert(ShoppingCar cart) {
        List<ShoppingCar> shoppingCars = shoppingCarMapper.selectByCart(cart);
        if (shoppingCars.size() == 0 || shoppingCars.isEmpty()){
            shoppingCarMapper.insert(cart);
        }else if (shoppingCars.size() == 1){
            cart.setCarCount(cart.getCarCount() + shoppingCars.get(0).getCarCount());
            shoppingCarMapper.update(cart);
        }

        return cart;
    }

    @Override
    public void update(ShoppingCar cart) {
        shoppingCarMapper.update(cart);
    }

    @Override
    public ShoppingCar selectByCartId(Integer cartId) {
        ShoppingCar shoppingCar = new ShoppingCar();
        shoppingCar.setCarId(cartId);
        List<ShoppingCar> shoppingCars = shoppingCarMapper.selectByCart(shoppingCar);
        ShoppingCar shoppingCar1 = shoppingCars.get(0);
        ProductPo productPo = productMapper.selectVo(shoppingCar1.getProductId());
        shoppingCar1.setProductPo(productPo);

        return shoppingCar1;
    }

    @Override
    public void delete(Integer carId) {
        shoppingCarMapper.delete(carId);
    }
}
